package com.quyeying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quyeying.entity.*;
import com.quyeying.mapper.TblPopularizeVideoDao;
import com.quyeying.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quyeying.utils.AsyncTask;
import com.quyeying.utils.RedisUtil;
import com.quyeying.utils.TokenUtil;
import com.quyeying.utils.httputils.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.quyeying.utils.result.R;
import com.quyeying.utils.result.ReturnPageData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 推广视频表 服务实现类
 * </p>
 *
 * @author skx
 * @since 2022-10-20
 */
@Service
public class TblPopularizeVideoServiceImpl extends ServiceImpl<TblPopularizeVideoDao, TblPopularizeVideoEntity> implements TblPopularizeVideoService {

    @Resource
    TblProductService productService;
    @Resource
    TblProductImageService productImageService;
    @Resource
    TblPraiseService praiseService;
    @Resource
    TblMerchantService merchantService;
    @Resource
    RedisUtil redisUtil;
    @Value("${oss.coverSuffix}")
    private String coverSuffix;
    @Resource
    private AsyncTask asyncTask;
    @Resource
    private TblFollowMerchantService tblFollowMerchantService;

    @Override
    public R findListByPage(HttpServletRequest request, Integer page, Integer pageCount, Long merchantId, String end) {
        Page<Map<String, Object>> byVideoMaps = baseMapper.findByVideoMaps(new Page<>(page, pageCount),coverSuffix, merchantId,end);
        setVideos(request, byVideoMaps.getRecords(), merchantId);
        return R.success(ReturnPageData.fillingData(byVideoMaps));
    }

    /**
     * 商户端-视频列表分页查询
     *
     * @param request
     * @param current
     * @param size
     * @return
     */
    @Override
    public R merchantVideoPage(HttpServletRequest request, Integer current, Integer size, String account, String end) {
        TblMerchantEntity merchantInfo = merchantService.getMerchantInfo(account);
        Page<Map<String, Object>> byVideoMaps = baseMapper.findByVideoMaps(new Page<>(current, size),coverSuffix, merchantInfo.getId(),end);
        return R.success(ReturnPageData.fillingData(byVideoMaps));
    }

    @Override
    public R add(TblPopularizeVideoEntity tblPopularizeVideoEntity, String account) {
        TblMerchantEntity merchantInfo = merchantService.getMerchantInfo(account);
        tblPopularizeVideoEntity.setMerchantId(merchantInfo.getId());
        baseMapper.insert(tblPopularizeVideoEntity);
        //发送发布消息
        TblMessageEntity messageEntity = new TblMessageEntity();
        messageEntity.setMerchantId(tblPopularizeVideoEntity.getMerchantId());
        messageEntity.setType(1);
        messageEntity.setJoinId(tblPopularizeVideoEntity.getId());
        asyncTask.sendMessage(messageEntity);
        return R.success();
    }

    @Override
    public R delete(Long id) {
        baseMapper.deleteById(id);
        return R.success();
    }

    @Override
    public R updateData(TblPopularizeVideoEntity tblPopularizeVideoEntity) {
        baseMapper.updateById(tblPopularizeVideoEntity);
        return R.success();
    }

    @Override
    public R findById(Long id) {
        TblPopularizeVideoEntity tblPopularizeVideoEntity = baseMapper.selectById(id);

        QueryWrapper<TblProductImageEntity> imageEntityQueryWrapper = new QueryWrapper<>();
        imageEntityQueryWrapper.eq("product_id", tblPopularizeVideoEntity.getPid()).orderByAsc("sort").last("limit 1");
        TblProductImageEntity imageEntity = productImageService.getOne(imageEntityQueryWrapper);
        if (!ObjectUtils.isEmpty(imageEntity)){
            tblPopularizeVideoEntity.setProductCover(imageEntity.getImageUrl());
        }
        if (!ObjectUtils.isEmpty(tblPopularizeVideoEntity.getPid())){
            TblProductEntity productEntity = productService.getProductInfo(Long.parseLong(tblPopularizeVideoEntity.getPid()));
            tblPopularizeVideoEntity.setProductName(productEntity.getProductName());
        }
        tblPopularizeVideoEntity.setCoverUrl(tblPopularizeVideoEntity.getVideo().concat(coverSuffix));
        return R.success(tblPopularizeVideoEntity);
    }

    /**
     * 获取最新商品视频分页接口
     *
     * @param page
     */
    @Override
    public Page<Map<String, Object>> newVideos(HttpServletRequest request, Page<Map<String, Object>> page, Long vid) {
        Page<Map<String, Object>> newVideos = baseMapper.newVideos(page, vid, coverSuffix);
        newVideos.setRecords(newVideos.getRecords().stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () ->new TreeSet<>(Comparator.comparing(m->m.get("id").toString()))
                        ),ArrayList::new
                )
        ));
        if (page.getCurrent() == 1) {
            QueryWrapper<TblPopularizeVideoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id, merchant_id as merchantId, video, video_desc as videoDesc, agree_num as agreeNum, " +
                            "share_num as shareNum, browse_num as browseNum," +
                            "create_time as createTime, pid, CONCAT(video,'"+coverSuffix+"') as coverUrl")
                    .eq("id", vid)
                    .orderByDesc("create_time").last("limit 1");
            Map<String, Object> map = getMap(queryWrapper);
            TblMerchantEntity merchant = merchantService.getById(Long.parseLong(map.get("merchantId").toString()));
            map.put("merchantName", merchant.getMerchantName());
            map.put("merchantHeadimg", merchant.getMerchantHeadimg());
            if(!ObjectUtils.isEmpty(map.get("pid"))) {
                QueryWrapper<TblProductImageEntity> imageEntityQueryWrapper = new QueryWrapper<>();
                imageEntityQueryWrapper.select("image_url as imageUrl")
                        .eq("product_id", map.get("pid"))
                        .orderByAsc("sort")
                        .last("limit 1");
                map.put("imageUrl", productImageService.getMap(imageEntityQueryWrapper).get("imageUrl"));
            }
            if(!ObjectUtils.isEmpty(newVideos.getRecords())) {
                newVideos.getRecords().add(0, map);
            }else {
                ArrayList<Map<String, Object>> maps = new ArrayList<>();
                maps.add(map);
                newVideos.setRecords(maps);
            }
        }
        setVideos(request, newVideos.getRecords(), 0L);
        return newVideos;
    }

    @Override
    public R updateShareNum(TblPopularizeVideoEntity tblPopularizeVideoEntity) {
        TblPopularizeVideoEntity tblPopularizeVideo = baseMapper.selectById(tblPopularizeVideoEntity.getId());
        tblPopularizeVideoEntity.setId(tblPopularizeVideo.getId());
        tblPopularizeVideoEntity.setShareNum(tblPopularizeVideo.getShareNum() + 1);
        baseMapper.updateById(tblPopularizeVideoEntity);
        return R.success();
    }

    @Override
    public R addVideoBrowseNum(HttpServletRequest request, Long videoId) {
            String ipAddress = HttpUtil.getIpAddress(request);
            String key = "VIDEO_BROWSE:".concat(String.valueOf(TokenUtil.verfiyToken(request) ? TokenUtil.getUserId(request)+videoId : videoId)).concat(ipAddress);
            if (!redisUtil.hasKey(key)) {
                //增加浏览量
                TblPopularizeVideoEntity tblPopularizeVideoEntity = new TblPopularizeVideoEntity();
                tblPopularizeVideoEntity.setId(videoId);
                tblPopularizeVideoEntity.setBrowseNum(getById(videoId).getBrowseNum() + 1);
                baseMapper.updateById(tblPopularizeVideoEntity);
                redisUtil.set(key, "1", 1800L);
            }
        return R.success();
    }

    @Override
    public R randomVideoList(HttpServletRequest request) {
        List<Map<String, Object>> byVideoMaps = baseMapper.randomVideoList(coverSuffix);
        setVideos(request, byVideoMaps, 0L);
        return R.success(byVideoMaps);
    }

    @Override
    public R findByVideoId(HttpServletRequest request, Long id) {
        Map<String, Object> byVideoId = baseMapper.findByVideoId(coverSuffix, id);
        ArrayList<Map<String, Object>> listMap = new ArrayList<>();
        listMap.add(byVideoId);
        setVideos(request, listMap, Long.valueOf(byVideoId.get("merchantId").toString()));
        return R.success(listMap.get(0));
    }

    /**
     * 设置视频列表信息
     * @param request
     * @param byVideoMaps
     * @return
     */
    private void setVideos(HttpServletRequest request, List<Map<String, Object>> byVideoMaps, Long merchantId) {
        byVideoMaps.forEach(map->{
            map.put("isPraise", false);
            map.put("isFollow", false);
            //如果登录状态，返回是否点赞过
            long userId = 0;
            if (TokenUtil.verfiyToken(request)) {
                userId = TokenUtil.getUserId(request);
                QueryWrapper<TblPraiseEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", userId).eq("video_id", map.get("id"));
                map.put("isPraise", praiseService.count(queryWrapper) > 0);
                //视频的商户是否关注
                //merchantId
                QueryWrapper<TblFollowMerchantEntity> followMerchantEntityQueryWrapper = new QueryWrapper<>();
                followMerchantEntityQueryWrapper.eq("user_id", userId).eq("merchant_id", map.get("merchantId"));
                map.put("isFollow", tblFollowMerchantService.count(followMerchantEntityQueryWrapper) > 0);
            }
            //商户信息
            if(ObjectUtils.isEmpty(merchantId)||merchantId>0) {
                Map<String, Object> merchantMap = merchantService.getMerchantMap(Long.parseLong(map.get("merchantId").toString()));
                map.put("merchantInfo", merchantMap);
            }
        });
    }
}
